﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SaunaClient.Model.Network;
using SaunaClient.View;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using SaunaClient.Controller.Communication;

namespace SaunaClient.View
{
    public partial class Form1 : Form
    {
        private const string MESSAGE_LOGIN_GREETING = "Welcome ";
        private const string MESSAGE_EXCLAMATION_MARK = "!";
        private const string MESSAGE_LOGOFF_STATUS = "Logoff Status";
        private ICommunicationManagerFactory communicationManagerFactory;
        private ICommunicationManager communicationManager;
        private const string COMMUNICATION_MANAGER = "CommunicationManager";
        private string serverDirectory;
        private string localDirectory;

        public Form1()
        {
            InitializeComponent();

            // Make user authentication controller
            communicationManagerFactory = new CommunicationManagerFactoryImplementation();
            communicationManager = communicationManagerFactory.Make(COMMUNICATION_MANAGER);

            // Initialize controls
            lblServerDirectory.Text = communicationManager.GetFtpServerDirectory();
            lblLocalDirectory.Text = communicationManager.GetFtpLocalDirectory();
            serverDirectory = communicationManager.GetFtpServerDirectory();
            localDirectory = communicationManager.GetFtpLocalDirectory();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();

            // Gets the file and stores them in a list
            lstUserFiles.BeginUpdate();
            lstUserFiles.Items.Add(openFileDialog1.FileName);
            lstUserFiles.EndUpdate();

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        //private void button2_Click(object sender, EventArgs e)
        //{   
        //    ftps.Upload(System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"\", System.IO.Path.GetFileName(openFileDialog1.FileName), serverDirectory);

        //}

        private void ServerFileList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void LocalFileList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            DialogResult downloadAgreement = MessageBox.Show(this, "Do you agree to Downloading the Selected files?", "User Agreement", MessageBoxButtons.YesNo);
            
           
            // Gets each highlighted file in
            if (downloadAgreement == DialogResult.Yes)
            {
                foreach (ListViewItem item in lstServerFiles.SelectedItems)
                {
                    String fileName = item.Text;
                    Console.WriteLine("text: " + fileName);
                    communicationManager.Download(serverDirectory, fileName, localDirectory);
                }
            }
           
        }
        // coders-project.blogspot.com/2008/06/messagebox-tuning-in-c.html
         
         




        private void btnUpdateList_Click(object sender, EventArgs e)
        {
            // Visual basic style　
            //Initialise list view 
            lstServerFiles.Clear();
            // Create column of list view
            // 80 is the size. Path is Column Name.
            lstServerFiles.Columns.Add("Path", 80);
            // Size is 80. Column name is Size
            lstServerFiles.Columns.Add("Size", 80);
            // Size for column time is 100
            lstServerFiles.Columns.Add("Time", 100);


            // Set  directory
            string strDirPath = communicationManager.GetServerFileList(serverDirectory);
            // Gets the list of the files on the local directory.
            string[] arraySelectedFiles = strDirPath.Split(new Char[] { '\n' });
            string fileName;
            string fileRealName;
            foreach (string oneFile in arraySelectedFiles)
            {
                //try catch for empty fields.
                try
                {
                    fileName = oneFile.Substring(39);
                    fileRealName = fileName.TrimEnd(new Char[] { '\r' });
                    // Creates a new listview item for each name
                    ListViewItem listViewItem = new ListViewItem(fileRealName);

                    // Gets the file detail information
                    string date = oneFile.Substring(18, 21);
                    listViewItem.SubItems.Add(date);
                    string size = oneFile.Substring(0, 17);
                    listViewItem.SubItems.Add(size);

                    //listViewItem.SubItems.Add(fileRealName);
                    lstServerFiles.Items.Add(listViewItem);
                }
                catch
                {

                }
            }
        }


        private void lstUserFiles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void serverList_TextChanged(object sender, EventArgs e)
        {

        }

        private void lstServerFiles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Read ftp base setting from file
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public object ReadFromFile(string filePath)
        {
            object obj = null;
            try
            {
                using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    IFormatter formatter = new BinaryFormatter();
                    obj = formatter.Deserialize(stream);
                }
            }
            catch (FileNotFoundException ex)
            {
                // Write error.
                Console.WriteLine(ex);
            }
            return obj;
        }

        /// <summary>
        /// Option menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetworkSetting networkSetting = communicationManager.ReadConfigFile();
            if (networkSetting == null)
            {
                // When Sauna configuration file does not exist, create network setting with default values
                networkSetting = new NetworkSetting();
            }

            ClientOptionForm clientOptionForm = new ClientOptionForm(networkSetting);

            if (clientOptionForm.ShowDialog() == DialogResult.OK)
            {
                // End Previous Communication
                communicationManager = null;

                // Recreate Communication Manager
                communicationManager = new CommunicationManager();

                networkSetting.Copy(clientOptionForm.networkSetting);
                communicationManager = communicationManagerFactory.Make(COMMUNICATION_MANAGER);

                lblServerDirectory.Text = networkSetting.FtpServerDirectory;
                
                serverDirectory = networkSetting.FtpServerDirectory;
                lblLocalDirectory.Text = networkSetting.FtpLocalDirectory;
                localDirectory = networkSetting.FtpLocalDirectory;

            }

        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            DialogResult uploadAgreement = MessageBox.Show(this, "Do you agree to Upload the Selected files?", "User Agreement", MessageBoxButtons.YesNo);
            
            // Gets each highlighted file in
            if (uploadAgreement == DialogResult.Yes)
            {
                foreach (ListViewItem item in lstUserFiles.SelectedItems)
                {
                    String userFileName = item.Text;
                    // Testing purposes: Console.WriteLine("text: " + fileName);
                    communicationManager.Upload(localDirectory, @"\" + userFileName, serverDirectory);
                }
            }

        }



        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoginForm loginForm = new LoginForm(communicationManager);

            if (loginForm.ShowDialog() == DialogResult.OK)
            {
                // Login succeed
                EnableClientGuiControls();
                ShowGreetingMessage(loginForm.LoginId);
            }
        }

        private void logoffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Logoff
            // Disable Client Gui Controls
            DisableClientGuiControls();
            ShowLogoffStatusMessage();
        }

        /// <summary>
        /// Enable Client Gui Controls
        /// </summary>
        private void EnableClientGuiControls()
        {
            btnDownload.Enabled = true;
            btnUpload.Enabled = true;
            btnUpdateList.Enabled = true;
            btnRefresh.Enabled = true;
        }

        /// <summary>
        /// Disable Client Gui Contorls
        /// </summary>
        private void DisableClientGuiControls()
        {
            btnDownload.Enabled = false;
            btnUpload.Enabled = false;
            btnUpdateList.Enabled = false;
            btnRefresh.Enabled = false;
        }

        /// <summary>
        /// Show Lonin Greeting Message
        /// </summary>
        private void ShowGreetingMessage(string loninId)
        {
            lblGreetingMessage.Text =
                MESSAGE_LOGIN_GREETING + loninId + MESSAGE_EXCLAMATION_MARK;

        }

        /// <summary>
        /// Show Logoff Message
        /// </summary>
        private void ShowLogoffStatusMessage()
        {
            lblGreetingMessage.Text = MESSAGE_LOGOFF_STATUS;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

            // Visual basic style　
            //Initialise list view 
            lstUserFiles.Clear();
            // Create column of list view
            // 80 is the size. Path is Column Name.
            lstUserFiles.Columns.Add("Path", 80);
            // Size is 80. Column name is Size
            lstUserFiles.Columns.Add("Size", 80);
            // Size for column time is 100
            lstUserFiles.Columns.Add("Time", 100);


            // Set local directory
            string strDirPath = localDirectory;
            // Get list of the files on the local directory.
            string[] strFileName = Directory.GetFiles(strDirPath);
            // Creates loop each directory name
            if (Directory.GetFiles(strDirPath).Length == 0)
            {
                return;
            }
            for (int i = 0; i < Directory.GetFiles(strDirPath).Length; i++)
            {
                // Creates a new listview item for each name
                ListViewItem listViewItem = new ListViewItem(Path.GetFileName(strFileName[i]));
                // Gets the file detail information
                FileInfo fileInfo = new FileInfo(strFileName[i]);
                listViewItem.SubItems.Add(fileInfo.Length.ToString());
                listViewItem.SubItems.Add(fileInfo.LastAccessTime.ToString());
                lstUserFiles.Items.Add(listViewItem);
            }

        }

        private void lstServerFiles_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void debugToolStripMenuItem_Click(object sender, EventArgs e)
        {


            btnDownload.Enabled = true;
            btnUpload.Enabled = true;
            btnUpdateList.Enabled = true;
            btnRefresh.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void lblUserFiles_Click(object sender, EventArgs e)
        {

        }

    }
}
    
        


